package com.github.xuemingyu.springboot.acticitycloud.service.impl;

import com.bidanet.bdcms.core.exception.CheckException;
import com.github.xuemingyu.springboot.acticitycloud.common.SqlQuery;
import com.github.xuemingyu.springboot.jkfaststart.common.LambdaQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author
 * @param <T>
 */
public abstract class BaseServiceImpl<T> {
    @Autowired
    LambdaQuery lambdaQuery;
    @Autowired
    SqlQuery sqlQuery;
    protected abstract JpaRepository<T, Long> getDao();

    public T findOne(Long id) {
        return this.getDao().findOne(id);
    }

    protected void errorMsg(String msg) {
        throw new CheckException(msg);
    }

    protected void checkNull(Object obj, String msg) {
        if (obj == null) {
            throw new CheckException(msg);
        }
    }


    public void update(Long id, Object updateObj) {
        T one = getDao().findOne(id);
        BeanUtils.copyProperties(updateObj, one);
        getDao().save(one);
    }

    protected void checkString(String str, String msg) {
        this.checkNull(str, msg);
        if (str.trim().isEmpty()) {
            throw new CheckException(msg);
        }
    }

    protected void checkPhone(String phone, String msg) {
        this.checkNull(phone, msg);
        if (!phone.matches("[0-9-()（）]{7,18}")) {
            throw new CheckException(msg);
        }
    }

    protected void checkIdCard(String idCard, String msg) {
        this.checkNull(idCard, msg);
        if (!idCard.matches("^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$")) {
            throw new CheckException(msg);
        }
    }
}
